<template>
  <el-dialog title="编辑" v-model="showDialog" @close="handleClose" width="600px" class="padding_10">
    <el-form :model="menu" label-width="80px" :rules="rules" ref="form">
      <el-form-item label="父菜单">
        <el-select v-model="menu.parent_id" clearable style="width:100%" placeholder="无父菜单">
          <el-option v-for="item in menus" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="menu.name" auto-complete="off" placeholder="请菜单名称"></el-input>
      </el-form-item>
      <el-form-item label="路由" prop="route">
        <el-input v-model="menu.route" auto-complete="off" placeholder="请输入路由"></el-input>
      </el-form-item>
      <el-form-item label="图标" prop="icon">
        <el-input v-model="menu.icon" auto-complete="off" placeholder="请输入图标"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model.number="menu.sort" auto-complete="off" placeholder="请设置排序"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose" size="medium">取 消</el-button>
        <el-button type="primary" @click="onSubmit()" size="medium">提 交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>

import { getTopMenu, addMenu, updateMenu } from '../../api/menu'
import { ElMessage } from "element-plus";
import { reactive, toRefs, onMounted, computed, watch, ref } from 'vue'

const props = defineProps({
  menu: {
    type: Object,
    default: {},
  },
  dialogVisible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(["reload"])

const state = reactive({
  showDialog: false,
  menus: [],
})

const rules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: "请设置排序", trigger: 'blur' },
    { type: 'number', message: '排序必须为数字值' }
  ],
}

watch(() => props.dialogVisible, (val) => state.showDialog = val)

const mode = computed(() => {
  return Boolean(props.menu.id) ? 'edit' : 'create'
})

const form = ref(null)

const onSubmit = () => {
  form.value.validate((valid) => {
    if (!valid) {
      console.log('error submit!!')
      return false
    }

    props.menu.parent_id = props.menu.parent_id || 0
    let execFun = props.menu.id ? updateMenu : addMenu;
    execFun(props.menu).then((result) => {
      if (result.status == 'success') {
        ElMessage.success("操作成功")
        emit('update:dialogVisible', false)
        emit('reload')
      } else {
        ElMessage.error(result.message)
      }
    })
  })
}

const handleClose = () => {
  form.value.resetFields()

  emit('update:dialogVisible', false)
}

getTopMenu().then(data => {
  state.menus = data.menus
})

const { showDialog, menus } = toRefs(state)

</script>
